package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.*;
import bean.Achievement;
import bean.Admin;
import bean.Exam;
import bean.Question;
public class AddQ extends HttpServlet{
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req,res);
	}
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		ExamDao edao=new ExamDao();
		List<Exam> allexam=edao.allExam();
		req.setAttribute("allexam", allexam);
	    int pageSize=10;
	    int showPage;
		QuestionDao dao=new QuestionDao();
		List<Question> all=dao.allQuestion();
		int recordCount=all.size();
		int pageCount=(recordCount%pageSize==0)?(recordCount/pageSize):(recordCount/pageSize+1);
		String integer=req.getParameter("showPage");
		
		String qid=req.getParameter("qid");
	    if(qid!=null&&qid!=""){
	    	try{
	    		dao.deleteQuestionByQid(qid);
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
	    }
	    
		if(integer==null){
			String eid=req.getParameter("eid");
			String question=req.getParameter("question");
			String keya=req.getParameter("keya");
			String keyb=req.getParameter("keyb");
			String keyc=req.getParameter("keyc");
			String keyd=req.getParameter("keyd");
			String answer=req.getParameter("answer");
			eid=new String(eid.getBytes("iso-8859-1"));
			question=new String(question.getBytes("iso-8859-1"));
			keya=new String(keya.getBytes("iso-8859-1"));
			keyb=new String(keyb.getBytes("iso-8859-1"));
			keyc=new String(keyc.getBytes("iso-8859-1"));
			keyd=new String(keyd.getBytes("iso-8859-1"));
			answer=new String(answer.getBytes("iso-8859-1"));
			Question q=new Question("",eid,question,keya,keyb,keyc,keyd,answer);
			try{
				dao.addQuestion(q);
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
			integer="1";
			  }
	    try{
	    	showPage=Integer.parseInt(integer);
	    }catch(NumberFormatException e){
	     showPage=1;
	    }
	    if(showPage<=1){
	     showPage=1;
	    }
	    if(showPage>=pageCount){
	     showPage=pageCount;
	    }
	   
	    if(showPage!=pageCount){
	    	int position=(showPage-1)*pageSize+1;
	    	ArrayList<Question> ql=dao.getOnePage(position, pageSize);
	    	req.setAttribute("qlist", ql);
	    }
	    else{
	    	int position=(showPage-1)*pageSize+1;
	    	ArrayList<Question> ql=dao.getLastPage(position);
	    	req.setAttribute("qlist", ql);
	    }
	    req.setAttribute("pageCount", pageCount);
	    req.setAttribute("showPage", showPage);
		req.getRequestDispatcher("questionmanage.jsp").forward(req,res);
	}
   

		
}
